<?php
/**
 * Class descript.
 * User: chan
 * Date: 2017/10/26 15:29
 */

namespace app\api\logic;
use app\api\BaseModel;
use think\Cache;
use app\api\validate\Circle as CircleValidate;


class Circle extends BaseModel
{
   /**
     * 菜品识别
     */
    public function foodInfo(){
        $file = request()->file('image');
        if(!$file) return array('message' => '图片不能为空');
        $file = $file->getFileInfo()->getPathname();
        $size = getimagesize($file);
        if(round($size[0]/$size[1],2) != round(660/490,2)) return array('message' => '图片比例不对');
        $token = $this->getToken();
        $url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' . $token;
        $img = file_get_contents($file);
        $img = base64_encode($img);
        $interface_value = db('interface_value')->where(array('type'=>'1'))->find();
        $bodys = array(
            'image' => $img,
            'top_num' => 5,
            'filter_threshold'=>$interface_value['param']
        );
        $res = json_decode($this->request_post($url, $bodys),true);
        if($res['result_num'] > 0){
            foreach($res['result'] as &$r){
                $r['probability'] = (string)round($r['probability'] * 100,2).'%';
            }
            return $res['result'];
        }else{
            return array();
        }
    }


    /**
     * 获取百度token
     */
    public function getToken(){
        if(!Cache::has('baidu_image_access_token')){
            $url = 'https://aip.baidubce.com/oauth/2.0/token';
            $post_data['grant_type']       = 'client_credentials';
            $post_data['client_id']      = config('baidu.client_id');
            $post_data['client_secret'] = config('baidu.client_secret');
            $o = "";
            foreach ( $post_data as $k => $v )
            {
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);
            $res = json_decode($this->request_post($url, $post_data));
            Cache::set('baidu_image_access_token',$res->access_token,$res->expires_in);
        }
        return Cache::get('baidu_image_access_token');


    }


    /**
     * 发起http post请求(REST API), 并获取REST请求的结果
     * @param string $url
     * @param string $param
     * @return - http response body if succeeds, else false.
     */
    private function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }


     /**
     * 生成美食图
     */
    public function createImage(){
        $spend_calories = db('member')->field('spend_calories')->where(['id' => $this->user['uid']])->find();
        $res = $this->checkData(
            ["food_name","calorie"],
            ["食物名称不能为空","卡路里不能为空"]
        );
        if(array_key_exists('message',$res)) return $res;
        $file = request()->file('image');
        if(!$file) return array('message' => '图片不能为空');
        $src = $file->getFileInfo()->getPathname();
        $size = getimagesize($src);
        if(round($size[0]/$size[1],2) != round(660/490,2)) return array('message' => '图片比例不对');
        $foods_info = array(
            'name' => $this->requestData['food_name'],
            'calorie' => $this->requestData['calorie'] > 0 ? '热量：'.($this->requestData['calorie']).'千卡/100克' : '热量：前方高能',
        );
        $im = imagecreatetruecolor(720, 780);
        $white = imagecolorallocate($im, 255, 255, 255);
        imagefill($im,0,0,$white);
        $src = imagecreatefromstring(file_get_contents($src));
        imagecopyresampled($im,$src,30,30,0,0,660,490,660,490);
        $font = "../public/static/index/font/FZKTJW.TTF";
        $color2 = imagecolorallocate($im, 153, 153, 153);
        if(!empty($this->requestData['food_name']) || !empty($this->requestData['calorie'])){
            $user_name = $this->user['nickname'];
            $name_num = mb_strlen($user_name,'utf8');
            if($name_num > 7){
                $user_name = mb_substr($user_name,0,7,'utf8');
            }
            $leng = imagettfbbox(17,0,$font,$user_name);
            $today_calorie_num = strlen($spend_calories['spend_calories']);
            $name_color = imagecolorallocate($im, 51, 51, 51);
            $color = imagecolorallocate($im, 116, 116, 116);
            $color1 = imagecolorallocate($im, 160, 59, 59);

            imagettftext($im,31,0,40,589,$name_color,$font,$foods_info['name']);
            imagettftext($im,31,0,40,589,$name_color,$font,$foods_info['name']);
            imagettftext($im,19,0,mb_strlen($foods_info['name']) * 40 + 77,589,$name_color,$font,$foods_info['calorie']);
            imagettftext($im,17,0,40,640,$color,$font,$user_name);
            imagettftext($im,17,0,40,640,$color,$font,$user_name);
            imagettftext($im,17,0,40,640,$color,$font,$user_name);
            imagettftext($im,17,0,0 + $leng[2] + 50,640,$color,$font,'：建议您');
            imagettftext($im,17,0,0 + $leng[2] + 50 + 92,640,$color,$font,'今天');
            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43,640,$color,$font,'共摄入的热量不超过');

            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43 + 205,640,$color,$font,$spend_calories['spend_calories']);
            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43 + 205,640,$color,$font,$spend_calories['spend_calories']);
            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43 + 205,640,$color,$font,$spend_calories['spend_calories']);

            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43 + 205 + $today_calorie_num * 11,640,$color,$font,'千卡哦！');
            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43 + 205 + $today_calorie_num * 11,640,$color,$font,'千卡哦！');
            imagettftext($im,17,0,0 + $leng[2] + 50 + 92 + 43 + 205 + $today_calorie_num * 11,640,$color,$font,'千卡哦！');

            imagettftext($im,17,0,40,676,$color,$font,'早餐吃好、午餐吃饱、晚餐吃少。请合理安排一日三餐！');
        }

        imagettftext($im,15,0,239,724,$color2,$font,'记  录  美  食  ，  记  录  美');
        imagettftext($im,15,0,244,753,$color2,$font,'--Photo By:AI美食相机--');

        $url = 'static/food_image/'.(microtime(true)*10000).$this->user['uid'].'.png';
        imagepng($im, ROOT_PATH . 'public/'.$url);
        /*销毁图片*/
        imagedestroy($im);

        $id = db('foods_circle_image')->insertGetId([
            'user_id' => $this->user['uid'],
            'image' => $url,
        ]);

        if(!$id) return array('message' => '系统错误');

        return array(
            'id' => $id,
            'image' => __ROOT__ . '/' .$url,

        );


    }

   //美食圈
   public function circle_list()
   {
      $data=array();

      if(!isset($this->requestData['page'])){
         $page=1;
      }else{
         $page=$this->requestData['page'];
      }

      $limit = 10;

      $page_start = ($page-1)*$limit;

      //where里面是屏蔽美食圈
   	  $total = db('foods_circle')->alias('fc')->join('member m','m.id = fc.user_id')->where('fc.del_time=0 and fc.id not in(select circle_id from af_foods_circle_shield where user_id = '.$this->user['userId'].') and fc.id not in(select id from af_foods_circle where user_id in (select shield_uid from af_foods_circle_shield where user_id = '.$this->user['userId'].'))')->count();

      $total_page = ceil($total/$limit);

      $result = db('foods_circle')->alias('fc')->join('member m','m.id = fc.user_id')->where('fc.del_time=0 and fc.id not in(select circle_id from af_foods_circle_shield where user_id = '.$this->user['userId'].') and fc.id not in(select id from af_foods_circle where user_id in (select shield_uid from af_foods_circle_shield where user_id = '.$this->user['userId'].'))')->limit($page_start, $limit)->order('fc.top desc,fc.create_time desc')->field('fc.*,m.nickname,m.headimage,m.id as mid')->select();

      foreach($result as $key=>$value){
         $result[$key]['create_time'] = date("H:m",$value['create_time']);

         if(!empty($value['images'])){
            $images = json_decode($value['images'],1);
            foreach($images as $k=>$v){
              //检测是否卡路里图片
              if(strpos($v,'static/food_image/') != 'false'){
                 $images[$k] = IMG_PATH.$v;
              }else{
                 $images[$k] = __ROOT__.'/'.$v;
              }
            }
            $result[$key]['images'] = $images;
         }else{

            $result[$key]['images'] = [];
         }

         //头像
         $result[$key]['headimage'] = get_headimage($value['headimage'],$value['mid']);

         //转发
         if(!empty($value['circle_id'])){
              $forward_circle_result = db('foods_circle')->where(array('id'=>$value['circle_id']))->field('id,user_id,content,images')->find();
              $member_result = db('member')->where(array('id'=>$forward_circle_result['user_id']))->field('nickname')->find();
              $forward_circle_result['nickname'] = $member_result['nickname'];

              if(!empty($forward_circle_result['images'])){
                    $images = json_decode($forward_circle_result['images'],1);
                    foreach($images as $k=>$v){
                        //检测是否卡路里图片
                        if(strpos($v,'static/food_image/') != 'false'){
                           $images[$k] = IMG_PATH.$v;
                        }else{
                           $images[$k] = __ROOT__.'/'.$v;
                        }
                    }
                    $forward_circle_result['images'] = $images;
              }else{
                    $forward_circle_result['images'] = [];
              }
              $result[$key]['forward_circle'] = $forward_circle_result;
         }else{
            $result[$key]['forward_circle'] = null;
         }


         //查询是否关注
         if($value['user_id'] == $this->user['userId']){
            $result[$key]['is_follow'] = 2;
         }else{
            //查询关注
            $follow_result = db('follow')->where(array('user_id'=>$this->user['userId'],'attention_id'=>$value['user_id']))->find();

            if(!empty($follow_result)){
              $result[$key]['is_follow'] = 1;
            }else{
              $result[$key]['is_follow'] = 0;
            }
         }

         //是否屏蔽
         $is_shield = db('foods_circle_shield')->where(array('circle_id'=>$value['id'],'user_id'=>$this->user['userId']))->find();

         if(!empty($is_shield)){
            $result[$key]['is_shield'] = 1;
         }else{
            $result[$key]['is_shield'] = 0;
         }

         //是否已点赞
         $circle_praise = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'circle_id'=>$value['id'],'type'=>'0'))->find();

         if(!empty($circle_praise)){
            $result[$key]['is_like'] = 1;
         }else{
            $result[$key]['is_like'] = 0;
         }

        //点赞数
        $circle_praise_count = db('foods_circle_praise')->where(array('circle_id'=>$value['id'],'type'=>'0'))->count();

        //评论数
        $circle_comment_count = db('foods_circle_comment')->where(array('c_id'=>$value['id'],'comment_id'=>'0'))->count();

        //转发数
        $forward_circle_count = db('foods_circle')->where(array('circle_id'=>$value['id']))->count();

        //点赞数
        $result[$key]['circle_praise_count'] = $circle_praise_count;

        //评论数
        $result[$key]['circle_comment_count'] = $circle_comment_count;

        //转发数
        $result[$key]['forward_circle_count'] = $forward_circle_count;

      }

      $data['list'] = $result;
      $data['total_page'] = $total_page;

      return $data;
   }

   //美食圈转发列表
   public function circle_forward_list()
   {
      (new CircleValidate())->checkCircleLikeParam();

      $circle_id = $this->requestData['circle_id'];

      $data=array();

      if(!isset($this->requestData['page'])){
         $page=1;
      }else{
         $page=$this->requestData['page'];
      }

      $limit = 10;

      $page_start = ($page-1)*$limit;

      $total = db('foods_circle')->alias('fc')
              ->join("member m","fc.user_id = m.id")
              ->where(array('fc.circle_id'=>$circle_id))->count();

      $total_page = ceil($total/$limit);

      $list = db('foods_circle')->alias('fc')
              ->join("member m","fc.user_id = m.id")
              ->where(array('fc.circle_id'=>$circle_id))->limit($page_start,$limit)->field('m.id,m.nickname,m.headimage')->select();

      $data['list'] = $list;
      $data['total'] = $total;
      $data['total_page'] = $total_page;

      return $data;
   }

   //美食圈详情
   public function circle_info()
   {
      (new CircleValidate())->checkCircleLikeParam();

      $circle_id = $this->requestData['circle_id'];

      $result = db('foods_circle')->where(array('id'=>$circle_id))->find();

      if(!empty($result['images'])){
            $images = json_decode($result['images'],1);
            foreach($images as $k=>$v){
                //检测是否卡路里图片
                if(strpos($v,'static/food_image/') != 'false'){
                   $images[$k] = IMG_PATH.$v;
                }else{
                   $images[$k] = __ROOT__.'/'.$v;
                }
            }
            $result['images'] = $images;
      }else{
            $result['images'] = [];
      }

      $result['creatime'] = date("h:i",$result['creatime']);

      //判断是否为关注人
      $follow_result = db('follow')->where(array('user_id'=>$this->user['userId'],'attention_id'=>$result['user_id']))->find();

      if(empty($follow_result)){
         //未关注
         if($this->user['userId'] == $result['user_id']){
            //是自己发布的
            $result['is_follow'] = 2;
         }else{
            $result['is_follow'] = 0;
         }
      }else{
         //已关注
         $result['is_follow'] = 1;
      }


      $forward_circle_count = db('foods_circle')->where(array('circle_id'=>$circle_id))->count();
      $circle_praise_count = db('foods_circle_praise')->where(array('circle_id'=>$circle_id,'type'=>'0'))->count();
      $circle_comment_count = db('foods_circle_comment')->where(array('c_id'=>$circle_id,'comment_id'=>'0'))->count();

      //转发数
      $result['forward_circle_count'] = $forward_circle_count;

      //点赞数
      $result['circle_praise_count'] = $circle_praise_count;

      //评论数
      $result['circle_comment_count'] = $circle_comment_count;

      //转发详情
      if(!empty($result['circle_id'])){
        $forward_circle_result = db('foods_circle')->where(array('id'=>$result['circle_id']))->field('id,user_id,content,images')->find();
        $member_result = db('member')->where(array('id'=>$forward_circle_result['user_id']))->field('nickname')->find();
        $forward_circle_result['nickname'] = $member_result['nickname'];

        if(!empty($forward_circle_result['images'])){
              $images = json_decode($forward_circle_result['images'],1);
              foreach($images as $k=>$v){
                //检测是否卡路里图片
                if(strpos($v,'static/food_image/') != 'false'){
                   $images[$k] = IMG_PATH.$v;
                }else{
                   $images[$k] = __ROOT__.'/'.$v;
                }
              }
              $forward_circle_result['images'] = $images;
        }else{
              $forward_circle_result['images'] = [];
        }

        $result['forward_circle'] = $forward_circle_result;

      }else{
        $result['forward_circle'] = null;
      }

      //美食圈详情发布者跟昵称
      $member_result = db('member')->where(array('id'=>$result['user_id']))->field('nickname,headimage')->find();
      $result['nickname'] = $member_result['nickname'];
      $result['headimage'] = get_headimage($member_result['headimage'],$result['user_id']);

      //是否已点赞
      $circle_praise_result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'circle_id'=>$circle_id,'type'=>'0'))->find();

      if(!empty($circle_praise_result)){
        $result['is_like'] = 1;
      }else{
        $result['is_like'] = 0;
      }

      return $result;
   }

   //添加美食圈
   public function add_circle()
   {
      //(new CircleValidate())->checkAddCircleParam();

      //卡路里图片
      if(isset($this->requestData['cid'])){
         $circle_image = db('foods_circle_image')->where(array('id'=>$this->requestData['cid']))->field('image')->find();
      }

   	$files = request()->file('image');

    if(!empty($circle_image)){
        $images[] = $circle_image['image'];
    }
   		
		if($files) {
		   foreach ($files as $file) {
		       $info = $file->move(ROOT_PATH . 'public' . DS . 'static' . DS . 'uploads');
		       if ($info) {
		           $images[] = str_replace('\\',"/",$info->getSaveName());
		       } else {
		           return array("message" => $file->getError());
		       }
		   }
		}



    if($files || !empty($circle_image))
    {
        $data['images']=json_encode($images);
    }
    
    $data['user_id'] = $this->user['userId'];
    $data['content'] = isset($this->requestData['content'])?$this->requestData['content']:"";
    $data['create_time'] = time();

    $result = db('foods_circle')->insert($data);

    if(!$result)return array('message'=>'发布美食圈失败');
   }

   //转发详情
   public function forward_circle_info()
   {
      (new CircleValidate())->checkCircleLikeParam();
      
      $foods_circle_result = db('foods_circle')->where(array('id'=>$this->requestData['circle_id']))->field('user_id,content,images')->find();

      $member=db('member')->where(array('id'=>$foods_circle_result['user_id']))->field('nickname')->find();

      if(!empty($foods_circle_result['images'])){
         $images = unserialize($foods_circle_result['images']);
         foreach($images as $k=>$v){
            //检测是否卡路里图片
            if(strpos($v,'static/food_image/') != 'false'){
               $images[$k] = IMG_PATH.$v;
            }else{
               $images[$k] = __ROOT__.'/'.$v;
            }
         }
         $foods_circle_result['images'] = $images[0];
      }

      $foods_circle_result['nickname'] = $member['nickname'];

      return $foods_circle_result;
   }


   //转发美食圈
   public function forward_circle()
   {
      (new CircleValidate())->checkForwardCircleParam();

      $data['user_id'] = $this->user['userId'];
      $data['circle_id'] = $this->requestData['circle_id'];
      $data['content'] = $this->requestData['content'];
      $data['creatime'] = time();

      $result = db('foods_circle')->insert($data);

      if(!$result)return array('message'=>'转发美食圈失败');
   }

   //美食圈点赞
   public function circle_like()
   {
      (new CircleValidate())->checkCircleLikeParam();

      $data['user_id'] = $this->user['userId'];
      $data['circle_id'] = $this->requestData['circle_id'];
      $data['type'] = '0';
      $data['creatime'] = time();

      $result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'circle_id'=>$this->requestData['circle_id']))->find();

      if(!empty($result)){
        $result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'circle_id'=>$this->requestData['circle_id']))->delete();
        $data_result['status'] = '0';
      }else{
        $result = db('foods_circle_praise')->insert($data);
        $data_result['status'] = '1';
      }
      if(!$result)return array('message'=>'发布美食圈点赞失败');
      return $data_result;
   }

   //美食圈关注人
   public function circle_follow()
   {
      (new CircleValidate())->checkCircleFollowParam();

      $data['user_id'] = $this->user['userId'];
      $data['attention_id'] = $this->requestData['attention_id'];
      $data['creatime'] = time();

      $result = db('follow')->where(array('user_id'=>$this->user['userId'],'attention_id'=>$this->requestData['attention_id']))->find();
      if(!empty($result)){
        $result = db('follow')->where(array('user_id'=>$this->user['userId'],'attention_id'=>$this->requestData['attention_id']))->delete();

        $data_follow['status'] = 0;
      }else{
        if($this->requestData['attention_id'] == $this->user['userId'])return array('message'=>'不能关注自己');
        $result = db('follow')->insert($data);

        $data_follow['status'] = 1;
      }

      if(!$result)return array('message'=>'关注失败');

      return $data_follow;
   }

   //美食圈屏蔽
   public function circle_shield()
   {
      if(!isset($this->requestData['shield_uid']) && !isset($this->requestData['circle_id']))return array('message'=>'屏蔽参数为空');
      if(!isset($this->requestData['shield_type']))return array('message'=>'shield_type参数为空');

      $shield_type_array = array('1','2');

      if(in_array($this->requestData['shield_type'], $shield_type_array)){

         if($this->requestData['shield_type'] == '1'){
            if($this->requestData['shield_uid'] == $this->user['userId'])array('message'=>'不能屏蔽自己');

            $result = db('foods_circle_shield')->where(array('user_id'=>$this->user['userId'],'shield_uid'=>$this->requestData['shield_uid']))->find();

            if(!empty($result))return array('message'=>'已屏蔽过此人了');
         }

         if($this->requestData['shield_type'] == '2'){
            $result = db('foods_circle_shield')->where(array('user_id'=>$this->user['userId'],'circle_id'=>$this->requestData['circle_id']))->find();

            if(!empty($result))return array('message'=>'该食圈已屏蔽了');
         }

         $data['shield_uid'] = isset($this->requestData['shield_uid'])?$this->requestData['shield_uid']:0;
         $data['circle_id'] = isset($this->requestData['circle_id'])?$this->requestData['circle_id']:0;
         $data['user_id'] = $this->user['userId'];

         $result = db('foods_circle_shield')->insert($data);
      }else{
         return array('message'=>'参数错误');
      }

      if(!$result)return array('message'=>'屏蔽失败');
   }

   //点击评论详情
   public function comment_info()
   {
      (new CircleValidate())->checkCommentLikeParam();

      $comment_id = $this->requestData['comment_id'];

      $list = $this->comment_list_info($comment_id);

      array_multisort(array_column($list,'id'),SORT_DESC,$list);

      foreach($list as $k=>$v){
        $list[$k]['create_time'] = date("h:i",$v['create_time']);
        $like_number = db('foods_circle_praise')->where(array('comment_id'=>$v['id'],'type'=>'1'))->count();
        $list[$k]['like_number'] = $like_number;

         //查询是否已经点赞
        $circle_praise_result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'comment_id'=>$v['id'],'type'=>'1'))->find();
        if(!empty($circle_praise_result)){
          $list[$k]['is_like'] = 1;
        }else{
          $list[$k]['is_like'] = 0;
        }
      }

      return $list;
   }

   //查询评论列表
   public function comment_list()
   {
      (new CircleValidate())->checkCircleLikeParam();
      
      $circle_id = $this->requestData['circle_id'];

      $data=array();

      if(!isset($this->requestData['page'])){
         $page=1;
      }else{
         $page=$this->requestData['page'];
      }

      $limit = 10;

      $page_start = ($page-1)*$limit;

      $total = db('foods_circle_comment')->where(array('c_id'=>$circle_id,'comment_id'=>'0'))->count();

      $total_page = ceil($total/$limit);

      $list = db('foods_circle_comment')->where(array('c_id'=>$circle_id,'comment_id'=>'0'))->limit($page_start, $limit)->order('id desc')->select();

      foreach($list as $k=>$v){
        $list[$k]['reply_comment_list'] = $this->comment_list_info($v['id']);
        array_multisort(array_column($list[$k]['reply_comment_list'],'id'),SORT_DESC,$list[$k]['reply_comment_list']);
        $list[$k]['reply_count'] = count($list[$k]['reply_comment_list']);
        $list[$k]['reply_comment_list'] = array_slice($list[$k]['reply_comment_list'],0,2);
        $list[$k]['create_time'] = date("h:i",$v['create_time']);
        $like_number = db('foods_circle_praise')->where(array('comment_id'=>$v['id'],'type'=>'1'))->count();
        $list[$k]['like_number'] = $like_number;
 

        //查询是否已经点赞
        $circle_praise_result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'comment_id'=>$v['id'],'type'=>'1'))->find();
        if(!empty($circle_praise_result)){
          $list[$k]['is_like'] = 1;
        }else{
          $list[$k]['is_like'] = 0;
        }
      }
      $data['list'] = $list;
      $data['total_page'] = $total_page;
      $data['total'] = $total;
      return $data;
   }

   //查询评论
   public function comment_list_info($comment_id,&$data = array())
   {
      $result = db('foods_circle_comment')->where(array('comment_id'=>$comment_id))->order('id desc')->select();

      if(!empty($result)){
         foreach($result as $k=>&$v){
            $reply_er = db('foods_circle_comment')->where(array('id'=>$v['comment_id']))->field('mem_name')->find();
            $result[$k]['reply_er'] = $reply_er['mem_name'];

            $data[] = $v;
            $this->comment_list_info($v['id'], $data);
         }
      }

      return $data;
   }

   //评论
   public function comment()
   {  
      (new CircleValidate())->checkForwardCircleParam();

      if(isset($this->requestData['comment_id'])){
         $data['comment_id'] = $this->requestData['comment_id'];
      }else{
         $data['comment_id'] = 0;
      }

      $data['c_id'] = $this->requestData['circle_id'];
      $data['content'] = $this->requestData['content'];
      $member_result = db('member')->where(array('id'=>$this->user['userId']))->field('headimage,nickname')->find();
      $data['mem_avatar'] = get_headimage($member_result['headimage'],$this->user['userId']);
      $data['mem_name'] = $member_result['nickname'];
      $data['create_time'] = time();

      $result = db('foods_circle_comment')->insert($data);

      if(!$result)return array('message'=>'评论失败');
   }

   //评论点赞
   public function comment_like()
   {
      (new CircleValidate())->checkCommentLikeParam();
      
      $comment_id = $this->requestData['comment_id'];

      $data['comment_id'] = $comment_id;
      $data['user_id'] = $this->user['userId'];
      $data['type'] = 1;
      $data['creatime'] = time();

      $circle_praise_result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'comment_id'=>$comment_id,'type'=>'1'))->find();

      if(!empty($circle_praise_result)){
        $result = db('foods_circle_praise')->where(array('user_id'=>$this->user['userId'],'comment_id'=>$comment_id,'type'=>'1'))->delete();
        $data_result['status'] = 0;
      }else{
        $result = db('foods_circle_praise')->insert($data);
        $data_result['status'] = 1;
      }

      if(!$result)return array('message'=>'点赞失败');

      return $data_result;
   }

   //举报详情
   public function report_info()
   {
      (new CircleValidate())->checkCircleLikeParam();

      $circle_id = $this->requestData['circle_id'];

      $foods_result = db('foods_circle')->where(array('id'=>$circle_id))->field('user_id,content')->find();
      $member_resul = db('member')->where(array('id'=>$foods_result['user_id']))->field('nickname')->find();
      $foods_result['nickname'] = $member_resul['nickname'];
      
      return $foods_result;
   }

   //举报
   public function report()
   {
      (new CircleValidate())->checkCircleLikeParam();

      $circle_id = $this->requestData['circle_id'];
      $type = $this->requestData['type'];

      $data['user_id'] = $this->user['userId'];
      $data['circle_id'] = $circle_id;
      $data['type'] = $type;

      $result = db('foods_circle_report')->insert($data);

      if(!$result)return array('message'=>'举报失败');
   }

   //用户删除食圈
   public function circle_del()
   {
        (new CircleValidate())->checkCircleLikeParam();
        $m_circle = db('foods_circle');
        $circle = $m_circle->where(['id' => intval($this->requestData['circle_id']),'del_time' => 0])->find();
        if(!$circle) return array('message' => '找不到食圈');
        if($circle['user_id'] != $this->user['id']) return array('message' => '无权操作');
        if($m_circle->where(['id' => intval($this->requestData['circle_id'])])->update(['del_time' => NOW_TIME]) === false) return array('message' => '删除失败');
        return array();
   }
}